package com.example.seakdreamandroid.whiteNoise;

import static com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService.NONE;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.sleep.Sleep;
import com.example.seakdreamandroid.voiceCommunity.VoiceRemarkActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/*
杨锐涵 白噪音眠友创作界面
 */
public class SleepFriendCreation extends Fragment implements  WhiteNoiseSleepFriendChannelAdapter.Callback {
    private static Context mContext;
    private static List<WhiteNoiseSleepFriendChannel> channels;
    private static WhiteNoiseSleepFriendChannelAdapter channelAdapter;

    private static ImageView sleepFriendPlay;
    private static ListView listView;

    private static SmartRefreshLayout smartRefreshLayout;
    private static boolean isRefresh = true;
    private String preparingChannelId = "";
    private WhiteNoisePlayerService.WhiteNoiseControl controller;
    private int count = 0;


    public SleepFriendCreation() {

    }
    public SleepFriendCreation( Context mContext) {
        this.mContext = mContext;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        WhiteNoisePlayerService.registerForListener(handler);
        //获取布局文件
        View view = inflater.inflate(R.layout.item_whitenoise_fragment_sleepfriend,container,false);
        //获取布局文件中的控件对象
        listView = view.findViewById(R.id.white_noise_fragment_sleepfriend);
        controller = WhiteNoisePlayerService.getController();
        //给控件对象设置必要的属性
        //给某些控件对象添加事件监听器
        //获取Channel数据源
        channels = new ArrayList<WhiteNoiseSleepFriendChannel>();
        setData();
        //实例化适配器对象

        channelAdapter = new WhiteNoiseSleepFriendChannelAdapter(
                mContext,
                channels,
                this
        );

        init(view);
        listView.setAdapter(channelAdapter);
        listView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //日志显示被点击的信息
                        //首先获取点击对象
                        WhiteNoiseSleepFriendChannel c = channels.get(position);

                        //其次日志显示获取到的对象
                        Log.i("msg",c.toString() + "     " + position);
                        //播放对应音频
                        startToTarActivity(position);
                    }
                }
        );
        setListener();
//        isCreate = true;


        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        WhiteNoisePlayerService.removeForListener(handler);
    }

    private void setListener() {
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时回调,需要请求最新的数据
                isRefresh = true;
                setData();
            }
        });
    }



    private void init(View view) {

        smartRefreshLayout = view.findViewById(R.id.sleep_friend_smart);
    }

    private boolean playingAudioIsThisChannel(){
        return WhiteNoisePlayerService.getChannel().equals("SleepFriendCreation");
    }

    public Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case WhiteNoisePlayerService.START_EVENT:
                    channelAdapter.notifyDataSetChanged();
                    //开始播放事件
                    break;
                case WhiteNoisePlayerService.PREPARED_EVENT:
                    //准备完成事件
                    channelAdapter.notifyDataSetChanged();
                    break;
                case WhiteNoisePlayerService.CONTINUE_EVENT:
                    //发生开始继续播放事件
                case WhiteNoisePlayerService.PAUSE_EVENT:
                    //发生暂停播放事件
                    if(playingAudioIsThisChannel()){
                        channelAdapter.notifyDataSetChanged();
                    }
                    break;
                case WhiteNoisePlayerService.ERROR_EVENT:
                    if(playingAudioIsThisChannel()){
                        channelAdapter.notifyDataSetChanged();
                    }
                    Toast.makeText(getActivity(),"播放器出错了，啥错我不知道",Toast.LENGTH_LONG).show();
                    break;

                case 5:
                    //更新adapter
                    channelAdapter.notifyDataSetChanged();
                    smartRefreshLayout.finishLoadMore();
                    break;
                case 6:
                    //刷新Listview
                    channelAdapter.notifyDataSetChanged();
                    smartRefreshLayout.finishRefresh();
                    break;
            }
        }
    };

    private void startToTarActivity(int position) {
        //创建Intent对象
        Intent intent = new Intent(getActivity(), VoiceRemarkActivity.class);
        //封装函数
        Bundle bundle = new Bundle();
        bundle.putSerializable("whiteSleep", channels.get(position));
        intent.putExtra("sleep",bundle);
        //跳转
        startActivity(intent);
    }
    private void setData(){
        String URL = Constant.BASE_URL + "WhiteNoise/SleepFriendCreation/findAllSleepFriendCreation";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URL)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("onFailure","请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responsseBody = response.body().string();
                response.close();
                Gson gson = new Gson();
                Type type = new TypeToken<List<SleepFriendChannel>>(){}.getType();
                List<SleepFriendChannel> sleepFriendChannels = gson.fromJson(responsseBody,type);
                Log.e(SleepFriendCreation.class.getName(),"channels.size = " + sleepFriendChannels.size());
                channels.clear();
                channels.addAll(0,getData(sleepFriendChannels));
                Message message = handler.obtainMessage();
                if (!isRefresh){
                    message.what = 5;
                }else{
                    message.what = 6;
                }
                handler.sendMessage(message);
            }
        });

    }

    private static List<WhiteNoiseSleepFriendChannel> getData(List<SleepFriendChannel> sleepFriendChannels) {
        List<WhiteNoiseSleepFriendChannel> list = new ArrayList<>();
        for(SleepFriendChannel sleepFriendChannel : sleepFriendChannels){
            WhiteNoiseSleepFriendChannel whiteNoiseSleepFriendChannel = new WhiteNoiseSleepFriendChannel();
            String URL = Constant.BASE_URL + "WhiteNoise/SleepFriendCreation/findUserInfoById/" + sleepFriendChannel.getUserId();
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(URL)
                    .build();
            Call call = okHttpClient.newCall(request);
            //这里没有用异步请求  异步请求很难拿到信息后进行更新
            Response response = null;
            try {
                response = call.execute();
                String responsseBody = response.body().string();
                Log.i(SleepFriendCreation.class.getName(),"userId=" + sleepFriendChannel.getUserId());
                Log.i(SleepFriendCreation.class.getName(),"responseBody = " + responsseBody);
                response.close();
                JSONObject result = new JSONObject(responsseBody);
                whiteNoiseSleepFriendChannel.setHead(result.getString("headshot"));
                whiteNoiseSleepFriendChannel.setUserName(result.getString("userName"));
                whiteNoiseSleepFriendChannel.setId(sleepFriendChannel.getId());
                whiteNoiseSleepFriendChannel.setSave(sleepFriendChannel.getSave()+"");
                whiteNoiseSleepFriendChannel.setCount(sleepFriendChannel.getCount()+"次");
                whiteNoiseSleepFriendChannel.setContent(sleepFriendChannel.getUserContent());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
                String date = simpleDateFormat.format(sleepFriendChannel.getPostTime());
                whiteNoiseSleepFriendChannel.setTime(date);
                whiteNoiseSleepFriendChannel.setTitle(sleepFriendChannel.getTitle());
                whiteNoiseSleepFriendChannel.setMusic1(sleepFriendChannel.getMusicImage1());
                whiteNoiseSleepFriendChannel.setMusic2(sleepFriendChannel.getMusicImage2());
                whiteNoiseSleepFriendChannel.setMusic3(sleepFriendChannel.getMusicImage3());
                whiteNoiseSleepFriendChannel.setSelectedId1(sleepFriendChannel.getSelectedId1());
                whiteNoiseSleepFriendChannel.setSelectedId2(sleepFriendChannel.getSelectedId2());
                whiteNoiseSleepFriendChannel.setSelectedId3(sleepFriendChannel.getSelectedId3());
                list.add(whiteNoiseSleepFriendChannel);
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
        return list;
    }




    @Override
    public void click(View v) {
        sleepFriendPlay = (ImageView) v;
        int position = (int) v.getTag();
        WhiteNoiseSleepFriendChannel channel = channels.get(position);
        Log.e(SleepFriendCreation.class.getName(),"第" + position + "个被选中");
        if (preparingChannelId.equals("")){
            if(channel.getId().equals(WhiteNoisePlayerService.getChannelInfoId())){
                Log.e(SleepFriendCreation.class.getName(),"playState=" + WhiteNoisePlayerService.getPlayState());
                switch(WhiteNoisePlayerService.getPlayState()){
                    case WhiteNoisePlayerService.NONE:
                        Toast.makeText(getActivity(),"没有要播放的白噪音，再去逛逛吧",Toast.LENGTH_SHORT).show();
                        break;
                    case WhiteNoisePlayerService.PREPARING:
                        Toast.makeText(getActivity(),"歌曲正在准备中，请稍等",Toast.LENGTH_SHORT).show();
                        break;
                    case WhiteNoisePlayerService.PLAYING:
                        controller.pausePlay(true);
                        break;
                    case WhiteNoisePlayerService.PAUSE:
                        controller.continuePlay(true);
                        break;
                }
            }else{
                count++;
                preparingChannelId = channel.getId();
                int countTemp = count;

                //获取详细的音频信息
                String URL = Constant.BASE_URL +  "WhiteNoise/FreeConbination/findFreeConbinationById/" + channel.getSelectedId1() + "/" + channel.getSelectedId2() + "/" + channel.getSelectedId3();
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(URL)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e("onFailure","请求失败");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String responseBody = response.body().string();
                        response.close();
                        Gson gson = new Gson();
                        Type type= new TypeToken<ArrayList<AudioInfo>>(){}.getType();
                        if(countTemp == count){
                            controller.play(gson.fromJson(responseBody,type),"SleepFriendCreation",channel.getId(),true);
                            preparingChannelId = "";
                        }else{
                            Log.i(SleepFriendCreation.class.getName(),"过期的请求结果，废弃");
                        }
                    }
                });
            }
        }else{
            //点击的是同一个
            if(preparingChannelId.equals(channel.getId())) {
                Toast.makeText(getActivity(), "歌曲信息正在加载中，稍等", Toast.LENGTH_SHORT).show();
            }else{
                count++;
                preparingChannelId = channel.getId();
                int countTemp = count;

                //获取详细的音频信息
                String URL = Constant.BASE_URL +  "WhiteNoise/FreeConbination/findFreeConbinationById/" + channel.getSelectedId1() + "/" + channel.getSelectedId2() + "/" + channel.getSelectedId3();
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(URL)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        Log.e("onFailure","请求失败");
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String responseBody = response.body().string();
                        response.close();
                        Gson gson = new Gson();
                        Type type= new TypeToken<ArrayList<AudioInfo>>(){}.getType();
                        if(countTemp == count){
                            controller.play(gson.fromJson(responseBody,type),"SleepFriendCreation",channel.getId(),true);
                            preparingChannelId = "";
                        }else{
                            Log.i(SleepFriendCreation.class.getName(),"过期的请求结果，废弃");
                        }
                    }
                });
            }
        }
    }

}
